package com.jiutong.meipenggang.ui.activitys;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.BaseActivity;
import com.jiutong.meipenggang.base.CommonAdapter;
import com.jiutong.meipenggang.base.ViewHolder;
import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.entity.InvestMoneyBean;
import com.jiutong.meipenggang.entity.InvestMoneySuccessBean;
import com.jiutong.meipenggang.http.model.interfaces.InvestMoneyBiz;
import com.jiutong.meipenggang.http.model.interfaces.InvestMoneySuccessBiz;
import com.jiutong.meipenggang.http.present.InvestMoneyPresent;
import com.jiutong.meipenggang.http.present.InvestMoneySuccessPresent;
import com.jiutong.meipenggang.utils.NumUilt;
import com.jiutong.meipenggang.utils.SpConfig;
import com.jiutong.meipenggang.views.dialog.BaseDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class InvestMoneyActivity extends BaseActivity implements InvestMoneyBiz,InvestMoneySuccessBiz {

    @Bind(R.id.rl_common_title_back)
    RelativeLayout rlCommonTitleBack;
    @Bind(R.id.tv_common_title)
    TextView tvCommonTitle;
    @Bind(R.id.tv_invest_money_total)
    TextView tvInvestMoneyTotal;
    @Bind(R.id.et_invest_money)
    EditText etInvestMoney;
    @Bind(R.id.btn_invest_all)
    Button btnInvestAll;
    @Bind(R.id.tv_invest_money_keyong)
    TextView tvInvestMoneyKeyong;
    @Bind(R.id.rl_invest_usable_hongbao)
    RelativeLayout rlInvestUsableHongbao;
    @Bind(R.id.tv_invest_money_pay)
    TextView tvInvestMoneyPay;
    @Bind(R.id.tv_invest_money_describe)
    TextView tvInvestMoneyDescribe;
    @Bind(R.id.tv_invest_money_ketou)
    TextView tvInvestMoneyKetou;
    @Bind(R.id.tv_invest_money_rongzi)
    TextView tvInvestMoneyRongzi;
    @Bind(R.id.tv_invest_money_chongzhi)
    TextView tvInvestMoneyChongzhi;
    @Bind(R.id.tv_invest_hongbao)
    TextView tvInvestHongbao;
    @Bind(R.id.ll_main)
    LinearLayout llMain;
    @Bind(R.id.iv_invest_money_yue)
    ImageView ivInvestMoneyYue;
    @Bind(R.id.rl_invest_money_yue)
    RelativeLayout rlInvestMoneyYue;
    @Bind(R.id.iv_invest_money_easy)
    ImageView ivInvestMoneyEasy;
    @Bind(R.id.iv_invest_money_easy_bank)
    ImageView ivInvestMoneyEasyBank;
    @Bind(R.id.rl_invest_money_easy)
    RelativeLayout rlInvestMoneyEasy;
    @Bind(R.id.tv_invest_money_yue_pay)
    TextView tvInvestMoneyYuePay;

    //可用余额
    private double keyong = 0;
    private BaseDialog dialog;
    //投资内容
    private String content;
    //投资金额
    private double investMoney = 0.0;
    //红包金额
    private double hongbaoMoney = 0.0;
    private PopupWindow mPopWindow;
    private HongbaoAdapter adapter;
    //红包总list
    private List<InvestMoneyBean.RedPrmListBean> mList = new ArrayList<>();
    //可用红包的list
    private List<InvestMoneyBean.RedPrmListBean> useList = new ArrayList<>();
    //红包当前位置
    private int currentIndex = -1;
    //实际支付金额
    private double pay = 0.0;

    //标的id
    private int bidId;
    //红包列表取消的LinearLayout
    private LinearLayout ll_cancel;
    private ListView rv_pop_hongbao;
    private TextView tv_cancel;
    //投资页面请求网络
    private InvestMoneyPresent investMoneyPresent;
    //投资期限
    private int period;
    //年利率
    private double apr;
    //我要投资请求网络
    private InvestMoneySuccessPresent investMoneySuccessPresent;
    //红包Id
    private String redId;

    //剩余可投金额
    private double overPlus = 0;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_invest_money;
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        super.initDate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            return;
        }
        bidId = bundle.getInt("bidId");
    }

    @Override
    protected void initView() {
        super.initView();
        tvCommonTitle.setText("投资金额");

    }

    @Override
    protected void onResume() {
        super.onResume();
        investMoneyPresent = new InvestMoneyPresent(this, this);
        investMoneyPresent.getInvestMoneyInfo();
        investMoneySuccessPresent = new InvestMoneySuccessPresent(this,this);

        //输入金额的监听事件
        etInvestMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框为空的时候，显示默认0.00
                //每次改变的时候，都把红包金额==0
                hongbaoMoney = 0;
                if (TextUtils.isEmpty(s)) {
                    tvInvestMoneyPay.setText("0.00元");
                    tvInvestMoneyYuePay.setVisibility(View.GONE);
                    investMoney = 0;
                    tvInvestMoneyTotal.setText("0.00");
                } else {
                    tvInvestMoneyYuePay.setVisibility(View.VISIBLE);
                    investMoney = Float.parseFloat(s.toString()); //输入的面值
                    //当输入金额大于剩余可投金额的时候，限制继续输入
                    if(investMoney>overPlus){
                        etInvestMoney.setText(String.valueOf(overPlus).substring(0,String.valueOf(overPlus).lastIndexOf(".")));
                    }

                    //判断是否有可用红包
                    useList.clear();
                    for (int i= 0;i<mList.size();i++){
                        if (investMoney>=mList.get(i).getRedRuleAmount()){
                            useList.add(new InvestMoneyBean.RedPrmListBean(mList.get(i).getRedRuleAmount(),
                                    mList.get(i).getEndTime(),mList.get(i).getRedHaveAmount(),mList.get(i).getRedName(),mList.get(i).getRedId()));
                        }
                    }
                    if(useList.size()>0){
                        tvInvestHongbao.setText("有"+useList.size()+"个可用红包");
                    }else{
                        tvInvestHongbao.setText("暂无可用红包");
                    }

                    //实际支付
                    pay = NumUilt.subtract(investMoney, hongbaoMoney, 2);
                    if (pay <= 0) {
                        tvInvestMoneyPay.setText("0.00元");
                    } else {
                        //实际支付
                        tvInvestMoneyPay.setText(NumUilt.formatBy2Scale(pay, 2) + "元");
                        //余额支付
                        tvInvestMoneyYuePay.setText("-"+NumUilt.formatBy2Scale(pay, 2)+"/");
                        if (apr != 0 && period != 0) {
                            //预计收益
                            double investTotalMoney = investMoney / 36000 * apr * period;
                            tvInvestMoneyTotal.setText(String.valueOf(NumUilt.formatBy2Scale(investTotalMoney, 2)));
                        }
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //默认选中余额支付
        ivInvestMoneyYue.setSelected(true);

    }


    @OnClick({R.id.rl_common_title_back, R.id.btn_invest_all, R.id.rl_invest_usable_hongbao, R.id.tv_invest_money_chongzhi, R.id.rl_invest_money_yue, R.id.rl_invest_money_easy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_common_title_back:
                finish();
                break;
            case R.id.btn_invest_all:  //全投
                //如果输入金额大于剩余可投金额，则全投的时候，默认改为剩余可投金额
                if(overPlus<=keyong){
                    etInvestMoney.setText(String.valueOf(overPlus).substring(0,String.valueOf(overPlus).lastIndexOf(".")));
                }else{
                    //默认只能输入正整数,如果可用余额中含有小数，修改为正整数
                    String allMoney = String.valueOf(keyong).substring(0,String.valueOf(keyong).lastIndexOf("."));
                    etInvestMoney.setText(allMoney);
                }
                break;
            case R.id.rl_invest_usable_hongbao:  //选择红包列表
                if(useList.size()>0){
                    //红包列表
                    showHongbaoDialog();
                }
                break;
            case R.id.tv_invest_money_chongzhi:  //我要投资
                if (investMoney != 0) {
                    //我要投资的dialog
                    investMoneySuccessPresent.investMoney(bidId+"",NumUilt.formatInt(investMoney+""),redId);

                } else {
                    toastShortShow("请输入投资金额");
                }
                break;
            case R.id.rl_invest_money_yue:  //余额支付
                ivInvestMoneyYue.setSelected(true);
                ivInvestMoneyEasy.setSelected(false);
                tvInvestMoneyYuePay.setVisibility(View.VISIBLE);
                break;
            case R.id.rl_invest_money_easy:  //快捷支付
                ivInvestMoneyEasy.setSelected(true);
                ivInvestMoneyYue.setSelected(false);
                tvInvestMoneyYuePay.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 我要投资显示的dialog
     */
    private void showDialog() {
        StringBuilder builder = new StringBuilder("您投");
        builder.append(NumUilt.formatDouble(investMoney));
        builder.append("元,在");
        builder.append(tvInvestMoneyDescribe.getText().toString().trim());
        content = builder.toString();
        dialog = new BaseDialog.Builder().
                layResuorce(R.layout.dialog_touzi).
                cancelViewClickEvent(R.id.tv_invest_dialog_cancel).
                okViewClickEvent(R.id.tv_invest_dialog_ok).
                confirmId(R.id.tv_invest_dialog_confirm).
                hintTextId(R.id.tv_invest_dialog_hint).
                contentTextId(R.id.tv_invest_dialog_content).
                llBottomId(R.id.ll_invest_dialog).
                confirmId(R.id.tv_invest_dialog_confirm).
                setHintText("投标成功").
                setContentText(content).
                setConfirmText("确定").
                gravityStyle(Gravity.CENTER).
                animResource(R.style.dialog_animation_fade).
                showOneOrTwoBtn(false).
                dialogWidth(-2).
                build();
        dialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
            @Override
            public void onOkClick() {
                if(dialog!=null){
                    dialog.dismiss();
                }
                openActivity(MainActivity.class);
                finish();
            }

            @Override
            public void onOk2Click() {

            }
        });

        dialog.show(getSupportFragmentManager(), TAG);
    }

    /**
     * 选择可用红包列表
     */
    private void showHongbaoDialog() {
        View contentView = LayoutInflater.from(InvestMoneyActivity.this).inflate(R.layout.pop_hongbao, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        ll_cancel = (LinearLayout) contentView.findViewById(R.id.ll_cancel);
        rv_pop_hongbao = (ListView) contentView.findViewById(R.id.lv_pop_hongbao);
        tv_cancel = (TextView) contentView.findViewById(R.id.tv_pop_cancel);
        mPopWindow.setContentView(contentView);
        mPopWindow.setFocusable(true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOutsideTouchable(true);
        if (useList.size() <= 0) {
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                }
            });
            ll_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                }
            });
        } else {
            //设置各个控件的点击响应
            adapter = new HongbaoAdapter(InvestMoneyActivity.this, useList, R.layout.invest_hongbao_item_list);
            rv_pop_hongbao.setAdapter(adapter);
            //Item点击时，把position赋值给currentIndex,并且传给Adapter，更新控件状态
            rv_pop_hongbao.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    currentIndex = position;
                    adapter.changeSelected(position);
                }
            });
            //两次选择不一致时，重新刷新adapter
            rv_pop_hongbao.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    adapter.changeSelected(position);
                    currentIndex = position;
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                    tvInvestHongbao.setText("");
                    hongbaoMoney = 0;
                    pay = NumUilt.subtract(investMoney, hongbaoMoney, 2);
                    if (pay <= 0) {
                        tvInvestMoneyPay.setText("0.00元");
                    } else {
                        tvInvestMoneyYuePay.setText(NumUilt.formatBy2Scale(pay, 2) +"/");
                        tvInvestMoneyPay.setText("-"+NumUilt.formatBy2Scale(pay, 2) + "元");
                    }
                }
            });
            //点空白页，读取选择红包的金额
            ll_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                    if (currentIndex >= 0) {
                        tvInvestHongbao.setText("￥" + useList.get(currentIndex).getRedHaveAmount());
                        hongbaoMoney = Double.parseDouble(String.valueOf(useList.get(currentIndex).getRedHaveAmount()));
                        pay = NumUilt.subtract(investMoney, hongbaoMoney, 2);
                        if (pay <= 0) {
                            tvInvestMoneyPay.setText("0.00元");
                        } else {
                            tvInvestMoneyPay.setText(NumUilt.formatBy2Scale(pay, 2) + "元");
                            tvInvestMoneyYuePay.setText("-"+NumUilt.formatBy2Scale(pay, 2) +"/");
                        }
                        redId = useList.get(currentIndex).getRedId();
                    }
                }
            });
        }

        mPopWindow.showAtLocation(llMain, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public int bidId() {
        return bidId;
    }

    /**
     * 投资页面数据返回
     * @param object
     */
    @Override
    public void onSuccess(Object object) {
        InvestMoneyBean bean = (InvestMoneyBean) object;
        if (bean.getError() == -1) {
            SpConfig.getInstance().edit().putString(Constants.ID, bean.getId()).commit();
            SpConfig.getInstance().edit().putString(Constants.TOKEN, bean.getToken()).commit();
            period = bean.getPeriod();
            apr = bean.getApr();
            //总融资金额
            tvInvestMoneyRongzi.setText("/融资" + NumUilt.formatInt(bean.getAmount() + ""));
            //账户余额
            keyong = bean.getBalance();
            tvInvestMoneyKeyong.setText(NumUilt.formatString(bean.getBalance() + "") + "元");
            //最低可投金额
            etInvestMoney.setHint(NumUilt.formatInt(bean.getMinInvestAmount() + "") + "元起投");
            //剩余可投金额
            overPlus  = bean.getInvestAmount();
            tvInvestMoneyKetou.setText("可投"+NumUilt.formatInt(overPlus + ""));
            //标题
            tvInvestMoneyDescribe.setText(bean.getTitle());
            mList = bean.getRedPrmList();
//            if(bean.isBindCardFlag()){
//                rlInvestMoneyEasy.setVisibility(View.VISIBLE);
//            }else{
//                rlInvestMoneyEasy.setVisibility(View.GONE);
//            }

        } else {
            toastShortShow(bean.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public int getOpt() {
        return 57;
    }

    /**
     * 投标结果返回
     * @param object
     */
    @Override
    public void investOnSuccess(Object object) {
        InvestMoneySuccessBean bean = (InvestMoneySuccessBean) object;
        if(bean.getError() == -1){
            SpConfig.getInstance().edit().putString(Constants.TOKEN,bean.getToken()).commit();
            showDialog();
        }else{
            toastShortShow(bean.getMsg());
        }
    }


    /**
     * 红包的适配器
     */
    public class HongbaoAdapter extends CommonAdapter<InvestMoneyBean.RedPrmListBean> {
        private ImageView iv_icon;
        private TextView tv_money;
        private TextView tv_describe;
        private TextView tv_reward;
        private TextView tv_limit_time;
        /**
         * 如果默认选中第一项，可以设置为0，不默认，设置为-1
         */
        private int mSelect = -1;

        public HongbaoAdapter(Context context, List<InvestMoneyBean.RedPrmListBean> listDatas, int layoutId) {
            super(context, listDatas, layoutId);
        }

        public void changeSelected(int positon) { //刷新方法
            if (positon != mSelect) {
                mSelect = positon;
                notifyDataSetChanged();
            }
        }

        @Override
        protected void fillData(ViewHolder holder, int position) {
            iv_icon = holder.getView(R.id.iv_invest_hongbao_ok);
            tv_money = holder.getView(R.id.tv_item_hongbao_money);
            tv_describe = holder.getView(R.id.tv_item_hongbao_describe);
            tv_reward = holder.getView(R.id.tv_item_hongbao_reward_money);
            tv_limit_time = holder.getView(R.id.tv_item_hongbao_limitday);
            //红包奖励金
            tv_money.setText(NumUilt.formatInt(listDatas.get(position).getRedHaveAmount() + ""));
            tv_describe.setText(listDatas.get(position).getRedName());
            //奖励规则
            tv_reward.setText("满" + NumUilt.formatInt(listDatas.get(position).getRedRuleAmount() + "") + "可用");
            tv_limit_time.setText(listDatas.get(position).getEndTime());
            if (mSelect == position) {
                iv_icon.setImageResource(R.mipmap.icon_out_selected);
            } else {
                iv_icon.setImageResource(R.mipmap.icon_out_unchecked);
            }
        }
    }



}
